//
//  WebViewController.swift
//  tanyue
//
//  Created by Macintosh on 2023/10/16.
//

import UIKit
import WebKit
import SnapKit

class WebViewController: UIViewController {
    
    var url: String!
    var isOneClick: Bool = false
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.white
        if(!isOneClick){
            showHUD()
        }
        
        view.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.width.equalTo(200)
            make.height.equalTo(40)
            make.top.equalTo(statusBarHeight)
        }
        
        let closeBtn = UIButton()
        closeBtn.setImage(UIImage(named: "delete_icon"), for: .normal)
        closeBtn.addTarget(self, action: #selector(actionBack), for: .touchUpInside)
        view.addSubview(closeBtn)
        closeBtn.snp.makeConstraints { make in
            make.width.height.equalTo(40)
            make.centerY.equalTo(titleLabel)
            make.right.equalTo(-10)
        }
        
        /// 设置访问的URL
        let u = URL(string: url)
        /// 根据URL创建请求
        let requst = NSURLRequest(url: u!)
        /// 设置代理
        webView.navigationDelegate = self
        /// WKWebView加载请求
        webView.load(requst as URLRequest)
        view.addSubview(webView)
        webView.snp.makeConstraints { make in
            make.top.equalTo(kNaviBarHieght)
            make.left.right.bottom.equalToSuperview()
        }
    }
    
    @objc
    func actionBack() {
        dismiss(animated: true)
    }
    
    lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor(hex: 0x111111)
        label.font = UIFont.systemFont(ofSize: 16)
        label.textAlignment = .center
        
        return label
    }()
    
    lazy var webView: WKWebView = {
        let webViewConfig = WKWebViewConfiguration()
        webViewConfig.allowsInlineMediaPlayback = true
        webViewConfig.mediaTypesRequiringUserActionForPlayback = .all
        let web = WKWebView(frame: .zero, configuration: webViewConfig)

        return web
    }()
    
}

extension WebViewController: WKNavigationDelegate {
    // 页面开始加载时调用
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!){
        
    }

    // 当内容开始返回时调用
    func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!){
        
    }

    // 页面加载完成之后调用
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!){
        /// 获取网页title
        titleLabel.text = webView.title ?? ""
        hideHUD()
    }
    
    // 页面加载失败时调用
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error){
        hideHUD()
    }
    
}
